<template>
  <div class="el_main_con">
    <Breadcrumb></Breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table border :data="roleList" stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdBottom', index1===0 ? 'bdTop':'', 'vcenter']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5" class="flexCenter">
                <el-tag closable @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级、三级权限 -->
              <el-col :span="19">
                <el-row :class="[index2===0 ? '':'bdTop','vcenter']" v-for="(item2,index2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="itemTag in item2.children" type="warning" :key="itemTag.id" closable @close="removeRightById(scope.row, itemTag.id)">
                      {{itemTag.authName}}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称">
        </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
        </el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <div class="controllerbox">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row)">编辑</el-button>
              <el-popconfirm title="确定删除改用户吗？" @onConfirm="deleteRole(scope.row)">
                <el-button slot="reference" type="danger" class="deleBtn" icon="el-icon-delete" size="mini">删除</el-button>
              </el-popconfirm>
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="openSetRoles(scope.row)">分配权限</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="编辑角色信息" :visible.sync="editRolesVisible" width="30%">
      <span slot="footer" class="dialog-footer">
        <el-form ref="editRolesForm" :model="editRolesForm" label-width="80px">
          <el-form-item label="角色名称">
            <el-input v-model="editRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input type="textarea" v-model="editRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="closeEditRolesVisible()">取 消</el-button>
        <el-button type="primary" @click="editRoles()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="添加角色信息" :visible.sync="addRolesVisible" width="30%">
      <span slot="footer" class="dialog-footer">
        <el-form ref="addRolesForm" :model="addRolesForm" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addRolesForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input type="textarea" v-model="addRolesForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="closeAddRolesVisible()">取 消</el-button>
        <el-button type="primary" @click="addRoles()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="分配权限" @close="setRolesVisibleClosed()" :visible.sync="setRolesVisible" width="50%">
      <span slot="footer" class="dialog-footer">
        <el-tree :data="treeList" ref="treeRef" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys"></el-tree>
        <el-button @click="setRolesVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoles()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Breadcrumb from 'components/breadcrumb/breadcrumb'
import { Authority } from '../../api/apiConfig'
export default {
  components: {
    Breadcrumb
  },
  data () {
    return {
      roleList: [],
      editRolesVisible: false,
      addRolesVisible: false,
      setRolesVisible: false,
      editRolesForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      treeList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defKeys: [],
      roleId: ''
    }
  },
  mounted () {
    this.getRoleList()
  },
  methods: {
    getRoleList () {
      Authority.getRoleList().then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.roleList = res.data
      })
    },
    // 根据ID删除对应权限
    removeRightById (role, rightId) {
      this.$confirm('确定删除该权限?', '提示', {
        type: 'warning'
      }).then(() => {
        const url = `roles/${role.id}/rights/${rightId}`
        Authority.deleteRolesByRightId(url).then(res => {
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.$message.success(res.meta.msg)
          // 建议使用第二种方式，第一种方式会存在刷新页面的情况，导致打开的权限列表被关闭
          // this.getRoleList()
          role.children = res.data
        })
      }).catch(() => { })
    },
    showEditDialog (roleInfo) {
      this.editRolesVisible = true
      this.editRolesForm = {
        id: roleInfo.id,
        roleName: roleInfo.roleName,
        roleDesc: roleInfo.roleDesc
      }
    },
    editRoles () {
      const url = `roles/${this.editRolesForm.id}`
      const params = {
        roleName: this.editRolesForm.roleName,
        roleDesc: this.editRolesForm.roleDesc
      }
      Authority.editRoles(url, params).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.editRolesVisible = false
        this.getRoleList()
      })
    },
    closeEditRolesVisible () {
      this.editRolesVisible = false
    },
    deleteRole (roleInfo) {
      const url = `roles/${roleInfo.id}`
      Authority.deleteRoles(url).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$refs.editRolesForm.resetFields()
        this.getRoleList()
      })
    },
    addRoles () {
      const params = {
        roleName: this.addRolesForm.roleName,
        roleDesc: this.addRolesForm.roleDesc
      }
      Authority.addRole(params).then(res => {
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$refs.addRolesForm.resetFields()
        this.addRolesVisible = false
        this.getRoleList()
      })
    },
    closeAddRolesVisible () {
      this.$refs.addRolesForm.resetFields()
      this.addRolesVisible = false
    },
    openSetRoles (role) {
      this.roleId = role.id
      const url = 'rights/tree'
      Authority.getrightsList(url).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.treeList = res.data
      })
      // 递归获取三级节点id
      this.getLeafKeys(role, this.defKeys)
      this.setRolesVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id,并保存到defkeys的数组中
    getLeafKeys (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听分配权限对话框关闭事件
    setRolesVisibleClosed () {
      this.defKeys = []
    },
    setRoles () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const url = `roles/${this.roleId}/rights`
      const params = {
        rids: idStr
      }
      Authority.addAuthority(url, params).then(res => {
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getRoleList()
      })
      this.setRolesVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.bdTop {
  border-top: 1px solid #eee;
}

.bdBottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}

.vcenter {
  display: flex;
  align-items: center;
}
.controllerbox {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
}
</style>
